package com.demo.minademo;

import android.content.Context;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

import java.lang.ref.WeakReference;
import java.net.InetSocketAddress;
import java.net.InterfaceAddress;

public class ConnectionManager {

    private ConnectionConfig mConfig;
    private WeakReference<Context> mContext;
    private NioSocketConnector mConnector;
    private IoSession mSession;
    private InetSocketAddress mAddress;

    public ConnectionManager(ConnectionConfig config){

        this.mConfig = config;
        this.mContext = new WeakReference<>(config.getContext());

        init();
    }

    private void init(){

        mAddress = new InetSocketAddress(mConfig.getIp(),mConfig.getPort());
        mConnector = new NioSocketConnector();
        mConnector.getSessionConfig().setReceiveBufferSize(mConfig.getReadBufferSize());
        mConnector.getFilterChain().addLast("logger",new LoggingFilter());
        mConnector.getFilterChain().addLast("codec",new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
        mConnector.setHandler(new DefaultHandler(mContext.get()));
        mConnector.setDefaultRemoteAddress(mAddress);


    }

    public boolean connect(){
        try {
            ConnectFuture future = mConnector.connect();
            future.awaitUninterruptibly();
            mSession = future.getSession();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        return mSession != null;
    }

    public void disConnect(){
        mConnector.dispose();
        mConnector = null;
        mSession = null;
        mAddress = null;
        mContext = null;
    }

}
